package com.framework.utils.pay.yunzhanghujiesuan;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

/**
 * 云结算加密
 */
public class YunJieSuanEncrypt {

        //加密算法
        public static byte[] TripleDesEncrypt(byte[] content, byte[] key) throws Exception {
            byte[] icv = new byte[8];
            System.arraycopy(key, 0, icv, 0, 8);
            return TripleDesEncrypt(content, key, icv);
        }
        protected static byte[] TripleDesEncrypt(byte[] content, byte[] key, byte[] icv) throws
                Exception {
            final SecretKey secretKey = new SecretKeySpec(key, "DESede");
            final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
            final IvParameterSpec iv = new IvParameterSpec(icv);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
            return cipher.doFinal(content);
        }
        //解密算法
        public static byte[] TripleDesDecrypt(byte[] content, byte[] key) throws Exception {
            byte[] icv = new byte[8];
            System.arraycopy(key, 0, icv, 0, 8);
            return TripleDesDecrypt(content, key, icv);
        }
        protected static byte[] TripleDesDecrypt(byte[] content, byte[] key, byte[] icv) throws
                Exception {
            final SecretKey secretKey = new SecretKeySpec(key, "DESede");
            final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
            final IvParameterSpec iv = new IvParameterSpec(icv);
            cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
            return cipher.doFinal(content);
        }
        //测试
        public static void main(String[] args) throws Exception {
            byte[] content = "{\"order_id\": \"201609010016562012987\",\"init_batch_id\":\"201609_-NDJ\",\"cur_batch_id\": \"201609_-NDJ\",\"issue_id\": \"201609-NDJ\",\"reserve_id\": \"56244623 20160901-1\",\"dealer_id\": \"sixcn\",\"broker_id\":\"0\",\"anchor_id\": \"56244623\",\"real_name\": \"张三\",\"card_no\":\"6228880199872220\",\"bank_name\": \"招商银⾏\",\"bank_branch\": \"上地分⾏\",\"bank_prov\": \"北京\",\"bank_city\": \"北京\",\"phone_no\": \"13488795491\",\"id_card\":\"123532612312312321\",\"yyyy_mm\": \"201609\",\"pay\": \"100000.00\"}".getBytes(StandardCharsets.UTF_8);
            byte[] key = "123456788765432112345678".getBytes(StandardCharsets.UTF_8);
            byte[] enc = YunJieSuanEncrypt.TripleDesEncrypt(content, key);
            System.out.println(enc);

            byte[] enc64 = Base64.encodeBase64(enc);
            System.out.println("encrypt: " + new String(enc64));
            byte[] dec64 = Base64.decodeBase64(enc64);
            byte[] dec = YunJieSuanEncrypt.TripleDesDecrypt(dec64, key);
            System.out.println("decrypt: " + new String(dec));
        }

}
